package system

import (
	"context"
	"os"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/sagoo-cloud/sagooiot/internal/consts"
	"github.com/sagoo-cloud/sagooiot/internal/dao"
	"github.com/sagoo-cloud/sagooiot/internal/model"
	"github.com/sagoo-cloud/sagooiot/internal/service"
)

type sSystemAppUpgrade struct{}

func sSystemAppUpgradeNew() *sSystemAppUpgrade {
	return &sSystemAppUpgrade{}
}
func init() {

	service.RegisterSystemAppUpgrade(sSystemAppUpgradeNew())
}

// GetAppUpgradeList 获取列表数据
func (s *sSystemAppUpgrade) GetAppUpgradeList(ctx context.Context, in *model.GetAppUpgradeListInput) (total, page int, list []*model.AppUpgradeOutput, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.AppUpgrade.Ctx(ctx)
		total, err = m.Count()
		if err != nil {
			err = gerror.New("获取总行数失败")
			return
		}
		page = in.PageNum
		if in.PageSize == 0 {
			in.PageSize = consts.PageSize
		}
		err = m.Page(page, in.PageSize).Order("created_at desc").Scan(&list)
		if err != nil {
			err = gerror.New("获取数据失败")
		}
	})
	return
}

// GetAppUpgradeById 获取指定ID数据
func (s *sSystemAppUpgrade) GetAppUpgradeById(ctx context.Context, id int) (out *model.AppUpgradeOutput, err error) {
	err = dao.AppUpgrade.Ctx(ctx).Where(dao.AppUpgrade.Columns().Id, id).Scan(&out)
	return
}

// AddAppUpgrade 添加数据
func (s *sSystemAppUpgrade) AddAppUpgrade(ctx context.Context, in model.AppUpgradeAddInput) (err error) {
	_, err = dao.AppUpgrade.Ctx(ctx).Insert(in)
	return
}

// EditAppUpgrade 修改数据
func (s *sSystemAppUpgrade) EditAppUpgrade(ctx context.Context, in model.AppUpgradeEditInput) (err error) {
	dao.AppUpgrade.Ctx(ctx).FieldsEx(dao.AppUpgrade.Columns().Id, dao.AppUpgrade.Columns().Path, dao.AppUpgrade.Columns().CreatedAt).Where(dao.AppUpgrade.Columns().Id, in.Id).Update(in)
	return
}

// DeleteAppUpgrade 删除数据
func (s *sSystemAppUpgrade) DeleteAppUpgrade(ctx context.Context, Ids []int) (err error) {

	for i := 0; i < len(Ids); i++ {
		out, err := s.GetAppUpgradeById(ctx, Ids[i])
		if err != nil {
			return err
		}
		err = os.Remove(out.Path)
		if err != nil {
			return err
		}
		_, err = dao.AppUpgrade.Ctx(ctx).Delete(dao.AppUpgrade.Columns().Id+" in (?)", Ids[i])
		if err != nil {
			return err
		}
	}

	return
}
